package org.example;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioChatClient {

    private static final String HOST = "localhost";
    private static final int PORT = 8080;

    public static void main(String[] args) {
        try (SocketChannel socketChannel = SocketChannel.open()) {
            socketChannel.connect(new InetSocketAddress(HOST, PORT));
            socketChannel.configureBlocking(false);

            String message = "Hello, NIO";
            sendMessage(socketChannel, message);
            System.out.println("发送消息: " + message);

            Thread.sleep(1000); // 给服务器一点时间来处理消息
            receiveMessage(socketChannel);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void sendMessage(SocketChannel channel, String msg) throws IOException {
        ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes("UTF-8"));
        channel.write(buffer);
    }

    private static void receiveMessage(SocketChannel channel) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int count = channel.read(buffer);
        if (count > 0) {
            buffer.flip();
            byte[] data = new byte[buffer.remaining()];
            buffer.get(data);
            String msg = new String(data, "UTF-8");
            System.out.println("收到回复: " + msg);
        }
    }
}